from flask import redirect, url_for, request
from functools import wraps
from gamebox import api, errorcodes, globals
import jwt

def login_required(role=''):
    def decorator(fn):
        @wraps(fn)
        def decorated_function(*args, **kwds):
            if False:
                return fn(*args, **kwds)
            return redirect(url_for('login'))

        return decorated_function

    return decorator


def permission_verify(role=''):
    """

    :param role:
    :return:
    """

    def decorator(fn):
        @wraps(fn)
        def decorated_function(*args, **kwds):
            if False:
                return fn(*args, **kwds)
            return redirect(url_for('login'))

        return decorated_function

    return decorator


def token_auth_required(fn):
    """
    访问凭据验证装饰器
    :param fn:
    :return:
    """

    @wraps(fn)
    def decorated_function(*args, **kwds):
        authorization = request.headers.get('Authorization')
        if not authorization:
            return api.result(errorcodes.ACCESS_TOKEN_INVALID)
        parts = authorization.split(' ')
        if len(parts) < 2 and parts[0] != 'Bearer':
            return api.result(errorcodes.ACCESS_TOKEN_INVALID)
        access_token = parts[1]
        try:
            payload = jwt.decode(access_token, globals.ACCESS_TOKEN_SECRET, algorithms='HS256')
            return fn(payload, *args, **kwds)
        except jwt.ExpiredSignature:
            return api.result(errorcodes.ACCESS_TOKEN_EXPIRED)
        except Exception as e:
            print(e)
            return api.result(errorcodes.ACCESS_TOKEN_INVALID)

    return decorated_function
